package _07_串;

public class _8_字符串转换整数atoi {

    public int myAtoi(String s) {
        s = s.trim();
        if (s.length() == 0) return 0;
        char[] chars = s.toCharArray();
        boolean negative = false;
        boolean isNum = false;
        // 判断第一个字符符号
        char first = chars[0];
        if (first == '-') {
            negative = true;
        } else if (first >= '0' && first <= '9') {
            isNum = true;
        } else if (first == '+') {
        } else {
            return 0;
        }
        long total = 0;
        int i = isNum ? 0 : 1;
        while (i < chars.length && chars[i] >= '0' && chars[i] <= '9' ) {
            total = total * 10 + (chars[i] - '0');
            if (negative && -total < Integer.MIN_VALUE) {
                return Integer.MIN_VALUE;
            }
            if (!negative && total > Integer.MAX_VALUE) {
                return Integer.MAX_VALUE;
            }
            i++;
        }
        return (int) (negative ? -total : total);
    }

}
